import { useSelector, useDispatch } from 'react-redux';
import styles from '../../assets/css/Doctor/DocEditInfo.module.css';
import { Button, Form, Input, Select, Space, Upload, message } from 'antd';
import { getDepartnames, getNurseInfoEdit } from '../../api/Nurse/NurseEditInfo';
import { useEffect, useState } from 'react';
import { setUser } from '../../stores/userSlice';

const { Option } = Select;
const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};

export default function DocEditInfo() {
    const user = useSelector((state) => state.userSlice.user);
    const dispatch = useDispatch();
    const [departnames, setDepartname] = useState([]);
    const [fileList, setFileList] = useState([
        {
            uid: '-1',
            name: 'defaultImage.jpg',
            status: 'done',
            header: user.head,
            url: user.head, // 默认显示的图片地址
        },
    ]);
    const [form] = Form.useForm();

    // 上传成功回调
    const handleSuccess = (response, file) => {
        console.log('上传成功', response);
        if (response.header_url) {
            setFileList([
                {
                    uid: file.uid,
                    name: file.name,
                    status: 'done',
                    header: response.header,
                    url: response.header_url, // 上传后的图片 URL
                },
            ]);
        }
    };

    const onFinish = async (values) => {
        // 先验证旧密码
        if (values.oldPassword && values.oldPassword !== user.password) {
            message.error('旧密码不正确');
            return;
        }

        const formData = {
            ...values,
            id: user.id,
            phone: user.phone,
            header: fileList[0]?.header, // 将图片的 URL 添加到表单数据中
        };
        const data = {
            name: formData.name,
            id: formData.id,
            idcard: formData.idcard,
            phone: formData.phone,
            department: formData.department, // 从表单中获取科室值
            oldpwd: formData.oldPassword,
            newpwd: formData.newPassword,
            head: formData.header.length > 20 ? undefined : formData.header,
        };

        const res = await getNurseInfoEdit(data);
        if (res.code === 1) {
            message.success(res.msg);
            dispatch(setUser({
                ...user,
                name: data.name,
                password: data.newpwd ? data.newpwd : user.password,
                head: fileList[0]?.url,
                idcard: data.idcard,
                department: data.department,
            }));
        }
    };
    const handleError = (error) => {
        message.error('上传失败，请稍后重试');
    };


    useEffect(() => {
        getDepartnames().then((res) => {
            setDepartname(res.data);
        });
    }, []);

    return (
        <div className={styles.body}>
            <Form
                {...layout}
                form={form}
                name="control-hooks"
                onFinish={onFinish}
                style={{
                    maxWidth: 600,
                }}
                initialValues={{
                    auth: user.purview,
                    account: user.account,
                    name: user.name,
                    idcard: user.idcard,
                    department: user.department, // 设置科室的默认值为用户当前科室
                }}
            >
                <Form.Item name="account" label="医生账号" rules={[{ required: false }]}>
                    <Input disabled />
                </Form.Item>
                <Form.Item name="auth" label="账号权限" rules={[{ required: false }]}>
                    <Select disabled allowClear>
                        <Option value="male">医生</Option>
                        <Option value="female">护士</Option>
                    </Select>
                </Form.Item>
                <Form.Item name="oldPassword" label="旧密码" rules={[{ required: false }]}>
                    <Input type="password" placeholder="请输入旧密码（不修改密码可以不用填写）" />
                </Form.Item>
                <Form.Item
                    name="newPassword"
                    label="新密码"
                    dependencies={['oldPassword']}
                    rules={[
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                                const oldPassword = getFieldValue('oldPassword');
                                if (oldPassword && !value) {
                                    return Promise.reject(new Error('请输入新密码'));
                                }
                                if (!oldPassword && value) {
                                    return Promise.reject(new Error('请先输入旧密码'));
                                }
                                return Promise.resolve();
                            },
                        }),
                    ]}
                >
                    <Input type="password" placeholder="请输入新密码（不修改密码可以不用填写）" />
                </Form.Item>
                <Form.Item name="name" label="姓名" rules={[{ required: true, message: '请输入姓名！' }]}>
                    <Input placeholder="请输入修改后的姓名" />
                </Form.Item>
                <Form.Item name="idcard" label="身份证号" rules={[{ required: true, message: '请输入身份证号！' }]}>
                    <Input placeholder="请输入修改后的身份证号" />
                </Form.Item>
                <Form.Item name="department" label="科室更改" rules={[{ required: true, message: '请选择科室！' }]}>
                    <Select
                        placeholder="选择修改后的科室"
                        allowClear
                        onChange={(value) => form.setFieldsValue({ department: value })}
                    >
                        {departnames?.map((ele) => (
                            <Option key={ele.name} value={ele.name}>
                                {ele.name}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="更改图片" valuePropName="fileList">
                    <Upload
                        listType="picture-card"
                        fileList={fileList}
                        maxCount={1}
                        showUploadList={false}
                        action={'http://hjj.ink:21099/users/uploadheader'}
                        method="POST"
                        onSuccess={handleSuccess}
                        onError={handleError}
                    >
                        <div>
                            {fileList.length > 0 && (
                                <img
                                    src={fileList[0].url}
                                    alt="avatar"
                                    style={{ width: '100%', height: '100%' }}
                                />
                            )}
                        </div>
                    </Upload>
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Space>
                        <Button type="primary" htmlType="submit">
                            确认修改
                        </Button>
                        <Button htmlType="button" onClick={() => history.back()}>
                            返回上一级
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
        </div>
    );
}
